package com.syqc.maps.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.LruCache
import com.koushikdutta.ion.Ion
import com.syqc.monitor.R

/** @author joker @date 2022/7/21 17:35$ */
object BitmapUtil {
    private var lruCache: LruCache<String, Bitmap?>? = null


    /** 初始化内存缓存 */
    fun initLruCache() {
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        lruCache = object : LruCache<String, Bitmap?>(maxMemory / 8) {
            override fun sizeOf(key: String?, value: Bitmap?): Int {
                return (value?.byteCount?:0) / 1024
            }

            override fun entryRemoved(
                evicted: Boolean, key: String,
                oldValue: Bitmap?, newValue: Bitmap?
            ) {
                super.entryRemoved(evicted, key, oldValue, newValue)
                oldValue?.recycle()
            }
        }
    }

    /**
     * 获取Bitmap
     *
     * @param context
     * @param imgUrl
     * @return
     */
    fun getBitmap(context: Context, imgUrl: String): Bitmap {
        if (lruCache == null) throw Exception("没有初始化 lruCache")

        var bitmap = lruCache!![imgUrl]
        if (bitmap == null) {
            try {
                bitmap = Ion.with(context).load(imgUrl).asBitmap().get()
                lruCache!!.put(imgUrl, bitmap)
            } catch (e:Exception) {
                bitmap =
                    BitmapFactory.decodeResource(context.resources, R.mipmap.ic_car_location_no)
            }
        }
        return bitmap!!
    }

    /** 清除缓存 */
    fun clearLruCache() {
        lruCache?.evictAll()
    }

}